//
//  CreateActivityVC.m
//  SelfDrivingTravelling-IOS
//
//  Created by Teplot_01 on 16/8/5.
//  Copyright © 2016年 Teplot_01. All rights reserved.
//

#import "CreateActivityVC.h"
#import "CreateActiviytCell.h"
#import "MSSCalendarViewController.h"
#import "MSSCalendarDefine.h"
@interface CreateActivityVC ()<UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate,UIImagePickerControllerDelegate,MSSCalendarViewControllerDelegate>

@end

@implementation CreateActivityVC
{
    UITableView *_tableView;
    UIButton *_leftBtn;
    UIButton *_rightBtn;
    
    CreateActiviytCell *_cell;
    UITextView *_gotoReasonTV;
    UITextView *_feeContainsTV;
    UITextView *_feeNotContainsTV;
    UITextView *_noticeTV;
    UITextView *_itineraryDirectionsTV;
    
    UIImageView *_iconImageView;
    NSString *_imgUrl;
    
    NSData *_dataAvatar;
    NSDictionary *_responseDic;
    
    NSInteger _startDate;
    NSInteger _endDate;
    NSString *_startTime;
    NSString *_endTime;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"发起活动";
    [self initTableView];
    
}
- (void)initTableView{
    _tableView = [[UITableView alloc]initWithFrame:self.view.frame];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
}
#pragma - mark UITableView Delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
        _cell = [[NSBundle mainBundle]loadNibNamed:@"CreateActiviytCell" owner:nil options:nil][0];
        _cell.selectionStyle = UITableViewCellSelectionStyleNone;
        _cell.activityLb.textColor = orangeTextColor;
        _cell.beginTimeLb.textColor = orangeTextColor;
        _cell.timeBtn.layer.borderWidth = 1;
        _cell.timeBtn.layer.borderColor = blackLineColore.CGColor;
        _cell.timeBtn.layer.cornerRadius = 3;
        [_cell.timeBtn setTitleColor:orangeTextColor forState:UIControlStateNormal];
        [_cell.timeBtn addTarget:self action:@selector(calendarAction) forControlEvents:UIControlEventTouchUpInside];
        _iconImageView = _cell.imageIcon;
        [_cell.addIconBtn addTarget:self action:@selector(addIconBtnAction) forControlEvents:UIControlEventTouchUpInside];
    
        UILabel *xindongLb = [[UILabel alloc]initWithFrame:CGRectMake(KScreenWidth/2 - 50, 310, 100, 30)];
        xindongLb.text = @"心动理由";
        xindongLb.textColor = orangeTextColor;
        xindongLb.textAlignment = NSTextAlignmentCenter;
        [_cell.contentView addSubview:xindongLb];
        _gotoReasonTV = [[UITextView alloc]initWithFrame:CGRectMake(8, 345, KScreenWidth-16, 150)];
        _gotoReasonTV.layer.borderWidth = 1;
        _gotoReasonTV.layer.borderColor = Theme_Color.CGColor;
        [_cell.contentView addSubview:_gotoReasonTV];
        
        UILabel *xingchengLb = [[UILabel alloc]initWithFrame:CGRectMake(KScreenWidth/2 - 50, 500, 100, 30)];
        xingchengLb.text = @"具体行程";
        xingchengLb.textColor = orangeTextColor;
        xingchengLb.textAlignment = NSTextAlignmentCenter;
        [_cell.contentView addSubview:xingchengLb];
        _itineraryDirectionsTV = [[UITextView alloc]initWithFrame:CGRectMake(8, 535, KScreenWidth-16, 150)];
        _itineraryDirectionsTV.layer.borderWidth = 1;
        _itineraryDirectionsTV.layer.borderColor = Theme_Color.CGColor;
        [_cell.contentView addSubview:_itineraryDirectionsTV];
        //
        UIButton *alterBtn = [[UIButton alloc]initWithFrame:CGRectMake(8, 535+150, 120, 30)];
        [alterBtn setTitle:@"行程发布样例" forState:UIControlStateNormal];
        [alterBtn setTitleColor:Red_Color forState:UIControlStateNormal];
        [alterBtn.titleLabel setFont:[UIFont systemFontOfSize:15]];
        [alterBtn addTarget:self action:@selector(alterBtnAction) forControlEvents:UIControlEventTouchUpInside];
        [_cell.contentView addSubview:alterBtn];
        
        UILabel *feiyongLb = [[UILabel alloc]initWithFrame:CGRectMake(KScreenWidth/2 - 50, 570+150, 100, 30)];
        feiyongLb.text = @"费用说明";
        feiyongLb.textColor = orangeTextColor;
        feiyongLb.textAlignment = NSTextAlignmentCenter;
        [_cell.contentView addSubview:feiyongLb];
        UILabel *baohanLb = [[UILabel alloc]initWithFrame:CGRectMake(8, 745, 100, 30)];
        baohanLb.text = @"包含";
        baohanLb.textColor = orangeTextColor;
        [_cell.contentView addSubview:baohanLb];
        _feeContainsTV = [[UITextView alloc]initWithFrame:CGRectMake(8, 780, KScreenWidth-16, 150)];
        _feeContainsTV.layer.borderWidth = 1;
        _feeContainsTV.layer.borderColor = Theme_Color.CGColor;
        [_cell.contentView addSubview:_feeContainsTV];
        UILabel *bubaohanLb = [[UILabel alloc]initWithFrame:CGRectMake(8, 935, 100, 30)];
        bubaohanLb.text = @"不包含";
        bubaohanLb.textColor = orangeTextColor;
        [_cell.contentView addSubview:bubaohanLb];
        _feeNotContainsTV = [[UITextView alloc]initWithFrame:CGRectMake(8, 970, KScreenWidth-16, 150)];
        _feeNotContainsTV.layer.borderWidth = 1;
        _feeNotContainsTV.layer.borderColor = Theme_Color.CGColor;
        [_cell.contentView addSubview:_feeNotContainsTV];

        UILabel *noticLb = [[UILabel alloc]initWithFrame:CGRectMake(KScreenWidth/2 - 50, 1125, 100, 30)];
        noticLb.text = @"特别注意";
        noticLb.textColor = orangeTextColor;
        noticLb.textAlignment = NSTextAlignmentCenter;
        [_cell.contentView addSubview:noticLb];
        _noticeTV = [[UITextView alloc]initWithFrame:CGRectMake(8, 1160, KScreenWidth-16, 150)];
        _noticeTV.layer.borderWidth = 1;
        _noticeTV.layer.borderColor = Theme_Color.CGColor;
        [_cell.contentView addSubview:_noticeTV];
        UILabel *tiaojianLb = [[UILabel alloc]initWithFrame:CGRectMake(KScreenWidth/2 - 60, 1315, 120, 30)];
        tiaojianLb.text = @"设置报名条件";
        tiaojianLb.textColor = orangeTextColor;
        tiaojianLb.textAlignment = NSTextAlignmentCenter;
        [_cell.contentView addSubview:tiaojianLb];
        
        _leftBtn = [[UIButton alloc]initWithFrame:CGRectMake(30, 1350, 120, 30)];
        [_leftBtn setImage:[UIImage imageNamed:@"selected.png"] forState:UIControlStateNormal];
        [_leftBtn setTitle:@"无条件报名" forState:UIControlStateNormal];
        _leftBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [_leftBtn setTitleColor:Theme_Color forState:UIControlStateNormal];
        _leftBtn.imageEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);
        [_leftBtn addTarget:self action:@selector(leftBtnAction) forControlEvents:UIControlEventTouchUpInside];
        [_cell.contentView addSubview:_leftBtn];
        
        _rightBtn = [[UIButton alloc]initWithFrame:CGRectMake(KScreenWidth-30-120, 1350, 120, 30)];
        [_rightBtn setImage:[UIImage imageNamed:@"unselected.png"] forState:UIControlStateNormal];
        [_rightBtn setTitle:@"仅俱乐部会员" forState:UIControlStateNormal];
        _rightBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [_rightBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        _rightBtn.imageEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);
        [_rightBtn addTarget:self action:@selector(rightBtnAction) forControlEvents:UIControlEventTouchUpInside];
        [_cell.contentView addSubview:_rightBtn];
        //完成Btn
        UIButton *doneBtn = [[UIButton alloc]initWithFrame:CGRectMake(10, 1390, KScreenWidth - 20, 40)];
        [doneBtn setTitle:@"完成" forState:UIControlStateNormal];
        [doneBtn addTarget:self action:@selector(requestForReleseActi) forControlEvents:UIControlEventTouchUpInside];
        doneBtn.tintColor = [UIColor whiteColor];
        doneBtn.backgroundColor = Theme_Color;
        [_cell.contentView addSubview:doneBtn];
        
        return _cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return 1430;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [_tableView endEditing:YES];
}
//调用日历
- (void)calendarAction{
    MSSCalendarViewController *cvc = [[MSSCalendarViewController alloc]init];
    cvc.limitMonth = 12 * 5;// 显示几个月的日历
    cvc.type = MSSCalendarViewControllerNextType;
    cvc.beforeTodayCanTouch = NO;// 今天之前的日期是否可以点击
    cvc.afterTodayCanTouch = YES;// 今天之后的日期是否可以点击
    cvc.startDate = _startDate;// 选中开始时间
    cvc.endDate = _endDate;// 选中结束时间
    cvc.showChineseHoliday = YES;// 是否展示农历节日
    cvc.showChineseCalendar = YES;// 是否展示农历
    cvc.showHolidayDifferentColor = YES;// 节假日是否显示不同的颜色
    cvc.showAlertView = YES;// 是否显示提示弹窗
    cvc.delegate = self;
    [self presentViewController:cvc animated:YES completion:nil];
}
- (void)calendarViewConfirmClickWithStartDate:(NSInteger)startDate endDate:(NSInteger)endDate{
    _startDate = startDate;
    _endDate = endDate;
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat: @"yyyy-MM-dd"];
    _startTime = [dateFormatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:_startDate]];
    _endTime = [dateFormatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:_endDate]];
    NSString *timeStr = [NSString stringWithFormat:@"%@%@%@",_startTime, @"--",_endTime];
//    NSLog(@"%@",timeStr);
    [_cell.timeBtn setTitle:timeStr forState:UIControlStateNormal];
}
//发布网络请求
- (void)requestForReleseActi{
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
    //参数
    NSMutableDictionary *parameters = [[NSMutableDictionary alloc]init];
    [parameters setValue:_cell.titleTF.text forKey:@"title"];
    [parameters setValue:_startTime forKey:@"stratTime"];
    [parameters setValue:_endTime forKey:@"endTime"];
    [parameters setValue:_cell.moneyTF.text forKey:@"cost"];
    [parameters setValue:@"1" forKey:@"status"];
    [parameters setValue:_gotoReasonTV.text forKey:@"gotoReason"];
    [parameters setValue:_cell.chufaCityTF.text forKey:@"departure"];
    [parameters setValue:_cell.mudiCityTF.text forKey:@"destination"];
    [parameters setValue:_cell.phoneTF.text forKey:@"advisoryPhone"];
    [parameters setValue:_feeContainsTV.text forKey:@"feeContains"];
    [parameters setValue:_feeNotContainsTV.text forKey:@"feeNotContains"];
    [parameters setValue:_noticeTV.text forKey:@"notice"];
    [parameters setValue:@"0" forKey:@"applyConditions"];
    [parameters setValue:_itineraryDirectionsTV.text forKey:@"itineraryDirections"];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager POST:@"http://115.28.152.130/tour/v1/activity/create.action" parameters:parameters success:^(NSURLSessionDataTask *operation, id responseObject) {
        _responseDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@>>>>",_responseDic);
        NSString *error = _responseDic[@"code"];
        if (![_responseDic[@"code"] isEqualToString:@"0000"]) {
            [SVProgressHUD showErrorWithStatus:[NSString errorStringWithCode:error]];
            
        }else{
            //请求成功
            [SVProgressHUD showSuccessWithStatus:@"请求成功"];
            //保存活动id
            NSNumber *activiId = _responseDic[@"activityId"];
            NSString *ActivityIdStr = activiId.stringValue;
            [ActivityIdStr saveToNSDefaultsWithKey:kActivityId];
            //上传头像
            [self uploadAvatarWithImage:_dataAvatar];
            [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeNone];
            
            [self performSelector:@selector(backToLastCtr) withObject:nil afterDelay:1];
        }
        
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"请求失败"];
        [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeNone];
    }];
}

//添加图片
- (void)addIconBtnAction{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"从相册中选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //
        [self LocalPhoto];
    }];
    UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //
        [self takePhoto];
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:albumAction];
    [alert addAction:photoAction];
    [alert addAction:cancel];
    [self presentViewController:alert animated:YES completion:nil];
}
//从相册选择
-(void)LocalPhoto{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    //资源类型为图片库
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    //设置选择后的图片可被编辑
    picker.allowsEditing = YES;
    [self presentViewController:picker animated:YES completion:nil];
}
//拍照
-(void)takePhoto{
    //资源类型为照相机
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    //判断是否有相机
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]){
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        picker.allowsEditing = YES;
        //资源类型为照相机
        picker.sourceType = sourceType;
        [self presentViewController:picker animated:YES completion:nil];
    }else {
        
    }
}
//取出图片
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //1.退出图片选择器
    [picker dismissViewControllerAnimated:YES completion:nil];
    //2.取出图片
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    [_iconImageView setImage:image];
    _dataAvatar = UIImageJPEGRepresentation(image,0.5);
    
}
//上传图片至服务器
- (void)uploadAvatarWithImage:(NSData *)imageAvatarData{
    //参数
    NSDictionary *parameters = @{
                                 @"activityId": _responseDic[@"activityId"],
                                 @"imgType": @"1",
                                 };
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager POST:@"http://115.28.152.130/tour/v1/activity/imgUpload.action" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileData:imageAvatarData name:@"file" fileName:[self getImgFileName] mimeType:@"image/png"];
    } success:^(NSURLSessionDataTask *task, id responseObject) {
        
        NSDictionary *imgUrlDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"<<<<<%@",imgUrlDic);
        NSString *error = imgUrlDic[@"code"];
        if (![imgUrlDic[@"code"] isEqualToString:@"0000"]) {
            [SVProgressHUD showErrorWithStatus:[NSString errorStringWithCode:error]];
        }else{
            //请求成功
            _imgUrl = imgUrlDic[@"imgUrl"];
            NSLog(@"<<<%@",_imgUrl);
            [SVProgressHUD showSuccessWithStatus:@"上传成功"];
            
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"请检查网络问题"];
    }];
}
- (NSString *)getImgFileName {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyyMMddHHmmss";
    NSString *str = [formatter stringFromDate:[NSDate date]];
    NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
    return fileName;
}
//Btn点击事件
- (void)leftBtnAction{
    [_rightBtn setImage:[UIImage imageNamed:@"unselected.png"] forState:UIControlStateNormal];
    [_rightBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_leftBtn setImage:[UIImage imageNamed:@"selected.png"] forState:UIControlStateNormal];
    [_leftBtn setTitleColor:Theme_Color forState:UIControlStateNormal];
}
- (void)rightBtnAction{
    [_leftBtn setImage:[UIImage imageNamed:@"unselected.png"] forState:UIControlStateNormal];
    [_leftBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_rightBtn setImage:[UIImage imageNamed:@"selected.png"] forState:UIControlStateNormal];
    [_rightBtn setTitleColor:Theme_Color forState:UIControlStateNormal];
}
- (void)alterBtnAction{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"行程发布样例" message:@"D1:第一天行程\nD2:第二天行程\nD3:第三天行程\nD4:第四天行程\nD5:第五天行程" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *doneAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action){
        //退出操作
        
        
    }];
    [alertController addAction:doneAction];
    [self presentViewController:alertController animated:YES completion:nil];
}
- (void)backToLastCtr{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
